package alloy.transform.atomize;

import java.util.Iterator;

import alloy.ast.ASTDepthFirstReplacer;
import alloy.ast.FindCommand;
import alloy.ast.Module;
import alloy.ast.Modules;
import alloy.ast.Specification;

public class AtomizePrePass extends ASTDepthFirstReplacer {
	/**
	 * Visits only the focus module of spec_, but looks at signatures from all
	 * modules in order to perform a correct atomization.
	 * 
	 * Commands within the focus module are NOT atomized. Visit those
	 * individually to do so.
	 */
	public Object visit(Specification spec_) {

		Modules modules = spec_.getModules();
		for (Iterator modIter = modules.getModuleIter(); modIter.hasNext();) {
			Module mod = (Module) modIter.next();
			AtomizationState.state._allSigs.add(mod.getSignatures());
		}

		Module focus = spec_.getFocus();

		focus.applyReturnVisitor(this);

		return spec_;
	}

	/**
	 * Visits the commands in module_
	 */
	public Object visit(Module module_) {
		// set the current module scope
		// _curModuleInfo = module_.getModuleInfo();

		// don't visit commands here anymore because of JIT atomization;
		// instead, initialize
		// the atomizationInfo fields of the commands so that when they are
		// atomized later,
		// each will have a copy of _allSigs.
		// (module_.getCommands()).applyReturnVisitor(this);
		for (Iterator commandIter = module_.getCommands().getCommandIter(); commandIter
				.hasNext();) {
			FindCommand command = (FindCommand) commandIter.next();
			command.moduleInfo = module_.getModuleInfo();
		}

		return module_;
	}

}
